<script lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import { User, Lock, Message } from '@element-plus/icons-vue';
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { registerService, loginService } from '@/api/user.js';
import { useTokenStore } from '@/stores/token.js';

export default {
    name: 'LoginVue',
    setup() {
        // 控制注册与登录表单的显示， 默认显示注册
        const isRegister = ref(false)
        const router = useRouter()
        const activeIndex = ref('1')
        const tokenStore = useTokenStore();
        const handleSelect = (key: string, keyPath: string[]) => {
            console.log(key, keyPath)
        }

        //用于登录的事件函数
        const login = async () => {
            try {
                let result = await loginService(registerData.value); // 调用登录服务
                ElMessage.success(result.msg ? result.msg : '登录成功')
                //把得到的token存储到pinia中
                tokenStore.setToken(result.data)
                router.push('/') // 登录成功后跳转到首页
            } catch (error) {
                ElMessage.error(`登录失败: 账号或密码错误`)// 登录失败提示，显示失败原因
            }
        }

        // 用于注册的事件函数
        const register = async () => {
            try {
                let result = await registerService(registerData.value); // 调用登录服务

                ElMessage.success(result.msg ? result.msg : '注册成功！')
            } catch (error) {
                ElMessage.error(`注册失败:${error.message}`)
            }
        }

        // 清空数据模型的数据
        const clearRegisterData = () => {
            try {
                registerData.value.username = '';
                registerData.value.email = '';
                registerData.value.password = '';
            } catch (error) {
                console.error('清空注册数据时发生错误:', error);
            }
        }

        // 处理注册点击事件
        const handleRegisterClick = () => {
            console.log('注册按钮被点击');
            isRegister.value = true;
        }

        // 处理返回点击事件
        const handleBackClick = () => {
            console.log('返回按钮被点击');
            isRegister.value = false;
        }

        // 监听 isRegister 的变化
        watch(isRegister, (newValue, oldValue) => {
            console.log(`isRegister 从 ${oldValue} 变更为 ${newValue}`);
        })

        // 用于注册的数据模型
        const registerData = ref({
            username: '',
            email: '',
            password: ''
        })

        // 用于注册的表单校验模型
        const registerDataRules = ref({
            username: [
                { required: true, message: '请输入用户名', trigger: 'blur' },
                { min: 5, max: 16, message: '用户名的长度必须为5~16位', trigger: 'blur' }
            ],
            email: [
                { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                {
                    validator: (rules, value, callback) => {
                        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // 正则表达式
                        if (!value) {
                            callback(new Error('请输入电子邮箱'));
                        } else if (!emailPattern.test(value)) {
                            callback(new Error('请输入正确的电子邮箱'));
                        } else {
                            callback();
                        }
                    },
                    trigger: 'blur'
                }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 5, max: 16, message: '密码长度必须为5~16位', trigger: 'blur' }
            ],
        })
        const open = () => {
            ElMessageBox.confirm(
                '该功能正在开发中……',
                '提示',
                {
                    confirmButtonText: 'OK',
                    type: 'warning',
                }
            )
        }
        return {
            isRegister,
            clearRegisterData,
            registerData,
            registerDataRules,
            handleRegisterClick,
            handleBackClick,
            login,
            register,
            User,
            Lock,
            Message,
            open
        }
    }
}
</script>


<template>
    <el-row class="login-page">
        <el-col :span="6" :offset="3" class="bg">
            <h1 class="description">编程无界限，接单更自由</h1>
            <p class="description_1">加入我们，开启你的远程工作之旅</p>
        </el-col>
        <el-col :span="6" :offset="4" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData"
                :rules="registerDataRules">
                <el-form-item>
                    <h1>Register</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input :prefix-icon="Message" type="email" placeholder="请输入电子邮箱"
                        v-model="registerData.email"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>

                <!-- 注册按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" @click="register" auto-insert-space>
                        注册
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false"
                        @click="isRegister = false; clearRegisterData(); handleBackClick()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 登录表单 -->
            <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="registerDataRules">
                <el-form-item>
                    <h1>Login</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入账号" v-model="registerData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="registerData.password"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" :underline="false" @click="open">忘记密码？</el-link>
                    </div>
                </el-form-item>

                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" @click="login" auto-insert-space>登录</el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="handleRegisterClick">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;

    .bg {
        background: url('@/assets/logo.jpg') no-repeat 60% 260px / 300px auto;
        border-radius: 0 20px 20px 0;
    }

    .description {
        margin-top: 490px; // 控制文字与logo之间的间距
        margin-left: 80px;
        font-size: 26px;
        color: #3532ed; // 设置文字颜色+  
    }

    .description_1 {
        margin-top: 30px; // 控制文字与logo之间的间距
        margin-left: 80px;
        font-size: 18px; // 设置文字大小
        color: #3532ed; // 设置文字颜色+  
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>